<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/11/14
 * Time: 17:10
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

class WarehouseAllot extends BaseModel
{
    protected $pk = 'allot_id';

    protected $autoWriteTimestamp = 'datetime';

    protected $insert = ['create_by', 'update_by'];

    protected $update = ['update_by'];

    /**
     * 待调拨
     * @var int
     */
    const ALLOT_STATUS_WAIT = 0;

    /**
     * 调拨中
     * @var int
     */
    const ALLOT_STATUS_ING = 10;

    /**
     * 待上架
     * @var int
     */
    const ALLOT_STATUS_WAIT_UP = 20;

    /**
     * 调拨完成
     * @var int
     */
    const ALLOT_STATUS_SUCC = 30;

    /**
     * 取消调拨
     * @var int
     */
    const ALLOT_STATUS_CANCEL = 40;

    public static $ALLOT_STATUS = [
        self::ALLOT_STATUS_WAIT => '待调拨',
        self::ALLOT_STATUS_ING => '调拨中',
        self::ALLOT_STATUS_WAIT_UP => '待上架',
        self::ALLOT_STATUS_SUCC => '调拨完成',
        self::ALLOT_STATUS_CANCEL => '取消调拨',
    ];

    protected function getStatusAttr($value)
    {
        return isset(self::$ALLOT_STATUS[$value])
            ? self::$ALLOT_STATUS[$value]
            : $value;
    }

    /**
     * 关联调拨详情
     * @return \think\model\relation\HasMany
     * @date 2021/01/01
     * @author longli
     */
    public function info()
    {
        return $this->hasMany(WarehouseTerpInfo::class, 'ref_id', 'allot_id')
            ->where("id_type", static::getTable());
    }

    /**
     * 关联调入仓库
     * @return \think\model\relation\BelongsTo
     * @date 2021/02/18
     * @author longli
     */
    public function win()
    {
        return $this->belongsTo(Warehouse::class, 'in_id', 'warehouse_id');
    }

    /**
     * 关联调出仓库
     * @return \think\model\relation\BelongsTo
     * @date 2021/02/18
     * @author longli
     */
    public function wout()
    {
        return $this->belongsTo(Warehouse::class, 'out_id', 'warehouse_id');
    }

    /**
     * 关联用户
     * @return \think\model\relation\BelongsTo
     * @date 2021/02/18
     * @author longli
     */
    public function user()
    {
        return $this->belongsTo(Admin::class, 'user_id', 'id');
    }

    /**
     * 关联国内快递
     * @return \think\model\relation\BelongsTo
     * @date 2021/03/18
     * @author longli
     */
    public function express()
    {
        return $this->belongsTo(ChannelExpress::class, 'express_id', 'express_id');
    }

    /**
     * 通过调拨单获取
     * @param string $allotSn 调拨单号
     * @return WarehouseAllot
     * @date 2021/01/01
     * @author longli
     */
    public static function getBySn($allotSn)
    {
        $allotSn = trim($allotSn);
        return static::where("allot_id", $allotSn)->whereOr("allot_sn", $allotSn)->find();
    }
}
